/*    BlueTx
 *
 *    Copyright (c) 2007 Sun Ribo <Sean.Sun@bea.com>
 *
 *
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "md5.h"
#include "struct.h"

char *getlic(char *key);
char* rtrim(char *str)
{
     int i;
     int len=strlen(str);
     for(i=len-1;i>=0;i--)
         if(str[i]==' ' || str[i] == '\n')
            str[i]= '\0';
         else
            break;
     return str;
}

int lic_check(LICENSE *lic)
{
	static char linestr[1024];
	const char key1[]="SEAN&YANG"; const char key2[]="SunRIbO";
	int i = 0;
	FILE * fp = NULL;
	char *ptr = NULL;
	static char license[128], ip[32], expiration[32], version[6], signature[128];

	fp = fopen(  "lic.txt", "r") ;
	if( fp == NULL ) return -1;

	while( fgets(linestr, 1024, fp) ) {
		if( ptr = strstr( linestr, "LICENSE=" ) ) {
			strcpy( license, ptr+strlen("LICENSE=") );
			strcpy( lic->license, rtrim(license) );
		}
		if( ptr = strstr( linestr, "IP=" ) ) {
			strcpy( ip, ptr+strlen("IP=") );
			strcpy( lic->ip, rtrim(ip) );
		}
		if( ptr = strstr( linestr, "EXPIRATION=" ) ) {
			strcpy( expiration, ptr+strlen("EXPIRATION=") );
			strcpy( lic->expiration, rtrim(expiration) );
		}
		if( ptr = strstr( linestr, "VERSION=" ) ) {
			strcpy( version, ptr+strlen("VERSION=") );
			strcpy( lic->version, rtrim(version) );
		}
		if( ptr = strstr( linestr, "SIGNATURE=" ) ) {
			strcpy( signature, ptr+strlen("SIGNATURE=") );
			strcpy( lic->signature, rtrim(signature) );
		}
	}
	fclose(fp);

	memset( linestr, 0, 1024 );
	sprintf( linestr, "%s%s%s%s%s\0", key2, lic->license, lic->ip, lic->expiration, lic->version );
	strcpy( linestr, getlic(linestr) );
	if( strlen(linestr) != strlen( signature ) ) return -1;
	else {
		for ( i = 0; i < strlen( linestr) ; i ++ ) {
			if( linestr[i] != signature[i] ) return -1;
		}
	}
	return 1;
}

char *getlic(char *str)
{
     struct MD5Context md5c;
     unsigned char ss[16];
     static char str1[33]="";
     int i;

     MD5Init( &md5c );
     MD5Update( &md5c, str, strlen(str) );
     MD5Final( ss, &md5c );

     for( i=0; i<16; i++ ) {
          sprintf(str1+i*2, "%02X", ss[i]);
     }
  	 return str1;
}
